package com.oyjd.fw.ws;

import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

/**
 * 客户端数据链处理示例
 * 
 * @author 欧建东 <B>Email oyjd@163.com</B>
 * 
 */
public class ClientHandler implements SOAPHandler<SOAPMessageContext> {

	public boolean handleMessage(SOAPMessageContext context) {
		boolean outboundProperty = ((Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)).booleanValue();
		SOAPMessage message = context.getMessage();
		try {
			if (outboundProperty) {
				SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();

				SOAPHeader header = envelope.getHeader();
				if (null == header) {
					header = envelope.addHeader();
				}
				// SOAPElement security = header.addChildElement("Security",
				// "wsse",
				// "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
				// SOAPElement usernameToken =
				// security.addChildElement("UsernameToken", "wsse");
				// usernameToken.addAttribute(new QName("xmlns:wsu"),
				// "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
				// SOAPElement username =
				// usernameToken.addChildElement("Username", "wsse");
				// username.addTextNode("TestUser");
				// SOAPElement password =
				// usernameToken.addChildElement("Password", "wsse");
				// password.setAttribute("Type",
				// "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
				// password.addTextNode("TestPassword");

				SOAPElement security = header.addChildElement("security","oyjd","Email:oyjd@163.com");
				SOAPElement username = security.addChildElement("userId");
				username.addTextNode("admin");
				SOAPElement password = security.addChildElement("pwd");
				password.addTextNode("123456");

				System.out.println("客户端发出请求==========>");
			} else {
				System.out.println("客户端收到回应==========>");
			}
			message.writeTo(System.out);
			System.out.println("");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	public boolean handleFault(SOAPMessageContext context) {
		return true;
	}

	public void close(MessageContext context) {

	}

	public Set<QName> getHeaders() {
		// TODO Auto-generated method stub
		return null;
	}
}
